from django.db.models import Q
from django.views import View
from rest_framework.generics import GenericAPIView, ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ViewSet, ModelViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, \
    RetrieveModelMixin

from .models import Friend
from .serializer import ContactInfoSerializer, FriendRequestSerializer
from users.models import User
from rest_framework import status
from contacts.models import FriendRequest


class ContactsList(APIView):
    def get(self, request):
        user = request.user
        qs = Friend.objects.filter(user=user)
        serializer = ContactInfoSerializer(qs, many=True)

        return Response({'code': status.HTTP_200_OK, 'data': serializer.data})


class SearchFriend(APIView):
    def get(self, request, searchInfo):
        if not searchInfo:
            return Response({'status': 400})
        searchResult = User.objects.filter(Q(mobile=searchInfo) | Q(email=searchInfo) | Q(username=searchInfo)).values(
            'id', 'username', 'avatar', 'email').first()
        if searchResult:
            return Response({'data': searchResult, 'status': 200})
        return Response({'status': 400})
    # def post(self, ):


class FriendRequestView(APIView):
    def get(self, request):
        qs = FriendRequest.objects.filter(receiver=request.user)
        serializer = FriendRequestSerializer(instance=qs, many=True)
        return Response({'code': 200, 'data': serializer.data})

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = FriendRequestSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'status': 'ok'}, status=status.HTTP_201_CREATED)


class FriendRequestViewDetail(APIView):
    def put(self, request, pk):
        user = request.user
        requesterId = request.data['requesterId']
        try:
            fq = FriendRequest.objects.get(pk=pk)
            uAdd = Friend.objects.update_or_create(user=user, friend_id=requesterId)
            fAdd = Friend.objects.update_or_create(user_id=requesterId, friend_id=user.id)

        except FriendRequest.DoesNotExist:
            return Response({'code': status.HTTP_404_NOT_FOUND, 'msg': '操作失败'})
        fq.agree = True
        fq.save()
        return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})

    def delete(self, request, pk):
        try:
            fq = FriendRequest.objects.get(pk=pk)
        except FriendRequest.DoesNotExist:
            return Response({'code': status.HTTP_404_NOT_FOUND, 'msg': '操作失败'})
        fq.delete()
        return Response({'code': status.HTTP_204_NO_CONTENT, 'msg': '删除成功'})
